# modbus_server.py
import asyncio
import logging
from pymodbus.server import StartAsyncTcpServer
from pymodbus.datastore import ModbusSequentialDataBlock, ModbusServerContext
from pymodbus.device import ModbusDeviceIdentification

# 配置日志
logging.basicConfig(level=logging.DEBUG)
_logger = logging.getLogger("pymodbus.server")

# 创建数据存储
store = ModbusSequentialDataBlock(0, [0] * 20)  # 初始化 20 个寄存器
context = ModbusServerContext(slaves={1: store}, single=True)

# 配置设备信息
identity = ModbusDeviceIdentification()
identity.VendorName = "Pymodbus"
identity.ProductCode = "PM"
identity.VendorUrl = "https://github.com/pymodbus-dev/pymodbus/"
identity.ProductName = "Pymodbus Server"
identity.ModelName = "Pymodbus Server"
identity.MajorMinorRevision = "3.8.10"

# 自定义请求处理逻辑
class CustomRequestHandler:
    def __init__(self, context):
        self.context = context

    async def handle_request(self, data):
        # 读取客户端写入的寄存器（假设请求存储在寄存器 0-9 中）
        request_data = self.context[1].getValues(3, 0, count=10)  # 读取寄存器 0-9
        request_str = ''.join(chr(byte) for byte in request_data).strip('\x00')  # 将寄存器值转换为字符串

        # 根据请求内容返回响应
        if request_str == "hello":
            response_str = "world"
        elif request_str == "nihao":
            response_str = "good"
        else:
            response_str = "unknown"

        # 将响应写入寄存器 10-19
        response_data = [ord(c) for c in response_str]
        self.context[1].setValues(3, 10, response_data)

# 启动服务器
async def run_server():
    handler = CustomRequestHandler(context)
    server = await StartAsyncTcpServer(
        context=context,
        identity=identity,
        address=("0.0.0.0", 502),
        request_tracer=handler.handle_request  # 使用自定义请求处理逻辑
    )
    _logger.info("Server started successfully")
    return server

if __name__ == "__main__":
    asyncio.run(run_server(), debug=True)